<?php
$postconf = "/etc/postfix/main.cf";


function readConf( $file ) {
        $file = file( $file );
        $settings = array();
        foreach ($file as $line) {
                trim($line);
                if($line[0] != '#') {
                        $words = explode(" ", $line);
                        if(trim($words[1]) == '=') {
                                $key = $words[0];
                                $value = implode(" ", array_slice($words, 2));
                                $settings[$key] = trim($value);
                        }
                }
        }
        return $settings;
}


function savebase() {
	global $postconf;
	$settings = readConf( $postconf );

	  // mydestination - trim
	$arr = explode(', ', $settings["mydestination"]);
	$arr = array_map('trim', $arr);
	$mydestination = $arr;

	// relay host
	if( isset($_POST['relayhost']) )
		$settings["relayhost"] = $_POST["relayhost"];

	// radera en mydestination
	if( isset($_GET['del']) && $_GET['del']=='mydestination' && isset($_GET['dest']) ) {
		$nr = array_search($_GET['dest'], $mydestination);
		if( $nr !== FALSE )
			unset( $mydestination[$nr] );
	}

	// en ny mydestination
	if( isset($_POST['b_new_domain']) ) {
		$mydestination[] = $_POST['new_domain'];
	}

	// my destination
	$settings["mydestination"] = implode(', ', $mydestination );

	// mydomain, ta en destination och undvik localhost
	if( trim($mydestination[0]) != 'localhost' )
		$settings["mydomain"] = $mydestination[0];
	else
		$settings["mydomain"] = end($mydestination);

	// spamskydd
	if( isset($_POST['spampoint']) ) {
		$spampoint = $_POST['spampoint'];
		$postmaster = file_get_contents('/etc/postfix/master.cf');
		if( $spampoint == 'false' ) {
			// Stäng av spamskydd i postfix-master
			$postmaster = preg_replace('/^smtp\s+inet\s+([n-]\s+)+smtpd$\s*\-o\s+content_filter=spamassassin\s*$/m', 
				'smtp      inet  n       -       -       -       -       smtpd', $postmaster);
			file_put_contents('/etc/postfix/master.cf', $postmaster);
		}
		else {
			// Är inte spamskydd aktiverat i postfixs masterfil så ska den aktiveras
			if( !preg_match('/^smtp\s+inet\s+([n-]\s+)+smtpd$\s*\-o\s+content_filter=spamassassin\s*$/m', $postmaster) ) {
				$postmaster = preg_replace('/^smtp\s+inet\s+([n-]\s+)+smtpd\s*$/m',
					"smtp      inet  n       -       n       -       -       smtpd\n\t-o content_filter=spamassassin", $postmaster);
				file_put_contents('/etc/postfix/master.cf', $postmaster);
			}
			//ställ in rätt spamskyddsnivå i spamassassin
			$spamlocal = file_get_contents('/etc/spamassassin/local.cf');
			$spamlocal = preg_replace('/^\s*required_score\s+\S+\s*$/m', "required_score $spampoint", $spamlocal);
			file_put_contents('/etc/spamassassin/local.cf', $spamlocal);
		}
		//ladda om spamassassin
		exec("/etc/init.d/spamassassin reload &");
	}
	
	// spara inställningarna
	$fp = fopen($postconf, "w");
	foreach($settings as $key => $value) {
		fwrite($fp, "$key = $value\n");
	}
	fclose($fp);

	//ladda om postfix
	exec("/etc/init.d/postfix reload &");
	
	info('saved');
}


function savefetch()
{
	if( isset($_POST['pollmin']) ) {
		$pollsec = intval($_POST['pollmin']) * 60;
		
		$fetchmailrc = file_get_contents("/etc/fetchmailrc");
		$new_fetchmailrc = preg_replace("/set daemon \d+/", "set daemon $pollsec", $fetchmailrc, 1);
		file_put_contents("/etc/fetchmailrc", $new_fetchmailrc);
		
		//ladda om fetchmail
		exec("/etc/init.d/fetchmail restart &");
		
		info('saved');
	}
}


function delfetch()
{
	if( isset($_GET['remote']) && isset($_GET['local']) && isset($_GET['host']) ) {
		$error = false;
		
		$remote = $_GET['remote'];
		$local = $_GET['local'];
		$host = $_GET['host'];

		$fetchmailrc = file_get_contents("/etc/fetchmailrc");

		$new_fetchmailrc = preg_replace("/poll $host proto [^\ ]+ user \"$remote\" password \"[^\"]+\" is \"$local\"\n/", "", $fetchmailrc, 1);


		if( !$error ) {
			file_put_contents("/etc/fetchmailrc", $new_fetchmailrc);

			//ska autostart av fetchmail stängas?
			if( !preg_match("/poll.*proto.*user.*password/", $new_fetchmailrc) ) {
				$fetchmailconf = file_get_contents("/etc/default/fetchmail");
				$new_fetchmailconf = preg_replace("/START_DAEMON=yes/", "START_DAEMON=no", $fetchmailconf, 1);
				file_put_contents("/etc/default/fetchmail", $new_fetchmailconf);
				exec("/etc/init.d/fetchmail stop &");
			}
			//ladda om fetchmail
			else {
				exec("/etc/init.d/fetchmail restart &");
			}

			info('saved');
		}
	}
}


function savechangefetch()
{
	if( isset($_POST['remote']) && isset($_POST['local']) && isset($_POST['host']) && isset($_POST['proto']) ) {
		$error = false;
		$new = true;

		$remote = $_POST['remote'];
		$local = $_POST['local'];
		$host = $_POST['host'];
		$proto = $_POST['proto'];
		if( isset($_POST['old_remote']) && isset($_POST['old_local']) && isset($_POST['old_host']) ) {
			$old_remote = $_POST['old_remote'];
			$old_local = $_POST['old_local'];
			$old_host = $_POST['old_host'];
			$new = false;
		}

		$fetchmailrc = file_get_contents("/etc/fetchmailrc");

		if( isset($_POST['passwd']) && $_POST['passwd'] != "" ) {
			$password = $_POST['passwd'];
		}
		else if( $new == false ) {
			if( preg_match("/poll $old_host proto [^\ ]+ user \"$old_remote\" password \"[^\"]+\" is \"$old_local\"/", $fetchmailrc, $arr) ) {
				$arr = explode(' ', $arr[0]);
				$password = substr($arr[7], 1, -1);
			}
			else {
				$error = true; // Finns ej
			}
		}
		else {
			$error = true; // Lösen måste fyllas i
		}

		if( !$error ) {
			if( $new == true )
				$new_fetchmailrc = $fetchmailrc."poll $host proto $proto user \"$remote\" password \"$password\" is \"$local\"\n";
			else
				$new_fetchmailrc = preg_replace("/poll $old_host proto [^\ ]+ user \"$old_remote\" password \"[^\"]+\" is \"$old_local\"/", "poll $host proto $proto user \"$remote\" password \"$password\" is \"$local\"", $fetchmailrc, 1);
			
		
			file_put_contents("/etc/fetchmailrc", $new_fetchmailrc);
			
			//ska fetchmail starta auto?
			if( preg_match("/poll.*proto.*user.*password/", $new_fetchmailrc) ) {
				$fetchmailconf = file_get_contents("/etc/default/fetchmail");
				$new_fetchmailconf = preg_replace("/START_DAEMON=no/", "START_DAEMON=yes", $fetchmailconf, 1);
				file_put_contents("/etc/default/fetchmail", $new_fetchmailconf);
			}

			//ladda om fetchmail
			exec("/etc/init.d/fetchmail restart &");

			info('saved');
		}
	}
}


function saveadvanced()
{
	global $postconf;
	$error = false;

	$settings = readConf( $postconf );

	if( isset($_POST['allow_only_own']) ) {
		if( isset($settings['mynetworks']) )
			 unset($settings['mynetworks']);
		$settings['mynetworks_style'] = 'subnet';
	}
	else {
		if( isset($settings['mynetworks_style']) )
			unset($settings['mynetworks_style']);

		if( !isset($settings['mynetworks']) )
			$settings["mynetworks"]  = '127.0.0.0/8';

		  // mynetworks - trim
		$arr = explode(', ', $settings["mynetworks"]);
		$arr = array_map('trim', $arr);
		$mynetworks = $arr;
		
	    // Om "lägg till"-nätverk har tryckts
		if( isset($_POST['b_new_net']) && $_POST['new_net_allow']!="") {
			$new_net = trim($_POST['new_net_allow']);
		
			//Kontrollerar adress
			$num="(25[0-5]|2[0-4]\d|[01]?\d\d|\d)";
			if (!preg_match("/^$num\\.$num\\.$num\\.$num\/(3[0-2]|[1-2]\d|\d)$/", $new_net)) {
				error('net_wrong_ip');
				$error = true;
			}
			else {
				$mynetworks[] = $new_net;
			}
		}

	    // Om borttagningskryss har tryckts
		if( isset($_GET['del']) && $_GET['del']=='mynetworks' && isset($_GET['net']) ) {
			$nr = array_search($_GET['net'], $mynetworks);
			if( $nr !== FALSE )
				unset( $mynetworks[$nr] );
		}

		$settings["mynetworks"] = implode(', ', $mynetworks );
	}

    // Spara inställningarna och starta om mailservrar
	if( !$error ) {
		$fp = fopen($postconf, "w");
		foreach($settings as $key => $value) {
			fwrite($fp, "$key = $value\n");
		}
		fclose($fp);

		//ladda om postfix
		exec("/etc/init.d/postfix reload &");

		info('saved');
	}
}


function saveemailgroups() {
	$path = '/etc/postfix/emailgroups';
	if (isset($_POST['b_new_emailgroup'])) {
		// Skapa ny mailgrupp och sätt den som inaktiv
		$string = '#'.'utskicksadress'.': user@example.se'."\n";
		file_put_contents($path, $string, FILE_APPEND);
	} else if( isset($_POST['entries'] ) ) {
		// Spara alla mailgrupper på nytt
		for ($i=0;$i<$_POST['entries'];$i++) {
			$addrstr = '';
			$name = trim($_POST['name_'.$i]);
			$addr = trim($_POST['addr_'.$i]);
			$active = (($_POST['active_'.$i]=='on')?'':'#');
			$delete = (isset($_POST['b_delete_'.$i])?1:0);

			// Check om namnet är felaktigt, isåfall ge felmeddelande
			if (!preg_match('/^[a-z0-9_-]*$/i',$name) && !$delete) {
				error('emailgroups_name');
				$error = 1;
			} else {
				// Skapa array av alla mailadresser
				$split = preg_split("/[\s,;]+/", $addr); 
				foreach ($split as $s) {
					if(!is_valid_email_address(trim($s)) && !$delete) {
						error('emailgroups_addr');
						$error = 1;
					}
					$addrstr .= $s.', ';
				}
				$addrstr = trim($addrstr, ' ,');
			}

			// Om maillistan inte ska tas bort läggs den till
			// + Kommentera ut mailgruppen om den ska tas bort
			if (!$delete) $string .= $active.$name.': '.$addrstr."\n";
		}
		// Om inga fel skett, spara konfiguration
		if (!$error) file_put_contents($path, $string);
	}
	// Om inga fel skett, kör postalias
	if (!$error) exec('/usr/sbin/postalias '.$path);

}

////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////


switch( $_GET['t'] ) {
default:
case 'base':
	savebase();
	break;
case 'fetchmail':
	if( isset($_POST['b_new_domain']) ) {
		$GET['t'] = 'changefetchmail';
	}
	else if( $_GET['del'] == 'fetchpost' ) {
		delfetch();
	}
	else
		savefetch();
	break;
case 'changefetchmail':
	savechangefetch();
	break;
case 'advanced':
	saveadvanced();
	break;
case 'emailgroups':
	saveemailgroups();
	break;
}
?>
